package com.uyayo.cms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uyayo.cms.entity.CmsTag;
import com.uyayo.cms.mapper.CmsTagMapper;
import com.uyayo.cms.model.CmsTagCondition;
import com.uyayo.cms.service.CmsTagService;
import com.uyayo.framework.core.service.impl.BaseServiceImpl;
import com.uyayo.framework.pagehelper.pojo.OrderBy;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.util.OrderByUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service("cmsTagService")
public class CmsTagServiceImpl  extends BaseServiceImpl<CmsTag> implements CmsTagService {


	private final CmsTagMapper cmsTagMapper;

	@Autowired
	public CmsTagServiceImpl(CmsTagMapper cmsTagMapper) {
		this.cmsTagMapper = cmsTagMapper;
	}
	

	@Override
	public List<CmsTag> selectTag(CmsTagCondition cmsTagCondition) {
		Example example = new Example(CmsTag.class);
		Criteria criteria = example.createCriteria();
		if(Objects.nonNull(cmsTagCondition.getStatus())){
			criteria.andEqualTo("status",cmsTagCondition.getStatus());
		}

		return cmsTagMapper.selectByExample(example);
	}
	
	@Override
	public PageBean<CmsTag> selectTagByPaging(Integer pageCurrent, Integer pageSize, String sort, String order, CmsTagCondition cmsTagCondition) {

		List<CmsTag> userList;
		//分页处理
		List<OrderBy> orderBies = new ArrayList<>();
		orderBies.add(new OrderBy("createTime", "create_time"));
		orderBies.add(new OrderBy("updateTime", "update_time"));

		OrderByUtil  orderByUtil = new OrderByUtil();
		String orderBy = orderByUtil.getOrderBy(orderBies, sort, order);
		PageHelper.startPage(pageCurrent, pageSize);
		
		Example example = new Example(CmsTag.class);
		if(!StringUtils.isEmpty(orderBy)){
			example.setOrderByClause(orderBy);
		}
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(cmsTagCondition.getName())){
			criteria.andLike("name","%"+ cmsTagCondition.getName()+"%");
		}

		if(cmsTagCondition.getBeginCreateTime()!=null || cmsTagCondition.getEndCreateTime()!=null){
			criteria.andBetween("createTime", cmsTagCondition.getBeginCreateTime(), cmsTagCondition.getEndCreateTime());
		}
		if(Objects.nonNull(cmsTagCondition.getStatus())){
			criteria.andEqualTo("status",cmsTagCondition.getStatus());
		}
		userList = cmsTagMapper.selectByExample(example);

		//取记录总条数
		PageInfo<CmsTag> pageInfo = new PageInfo<>(userList);
		
		return new PageBean<>(pageInfo.getTotal(), pageCurrent, pageSize, userList);
	}

	@Override
	public List<CmsTag> selectCmsTagListByArticleId(Long articleId) {
		return cmsTagMapper.selectCmsTagList(articleId);
	}

}
